package com.example.shop.es;

import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

public class Writer {

    private static boolean isDateType(Object obj){
        if(obj instanceof LocalDate || obj instanceof LocalTime || obj instanceof LocalDateTime
                || obj instanceof Date){
            return true;
        }
        return false;
    }
    private static final boolean isPrimitive(Object obj){
        //isPrimitive是判断int的基本类型，而不能判断Integer的封装类
        if(obj != null && (obj.getClass().isPrimitive() ||
                obj instanceof Long || obj instanceof Float || obj instanceof Integer  || obj instanceof Double ||
                obj instanceof String || obj instanceof Character ||
                obj instanceof Byte || obj instanceof Short)){
            return true;
        }
        return false;
    }

    public static void write(XContentBuilder b, Object v) throws IOException {
        b.startObject();
        Class<?> aClass = v.getClass();
        do {
            Field[] fields = aClass.getDeclaredFields();
            for(Field field:fields){
                field.setAccessible(true);
                try {
                    Object fieldValue = field.get(v);
                    if(isDateType(fieldValue)){
                        //日期类型
                        b.field(field.getName(),fieldValue!=null?fieldValue.toString():null);
                    }else if(isPrimitive(fieldValue)){
                        //基础类型
                        b.field(field.getName(),fieldValue);
                    }else{
                        //否则是复杂类型
                        b.field(field.getName());
                        if(fieldValue!=null){
                            write(b,fieldValue);
                        }else{
                            b.nullValue();
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            aClass = aClass.getSuperclass();
        }while (aClass.getClassLoader()!=null);
        b.endObject();
    }
}
